package com.maxima.maximaAttendance.reports;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.struts2.ServletActionContext;

import com.maxima.maximaAttendance.daos.HolidayDAO;
import com.maxima.maximaAttendance.daos.TimeLogDAO;
import com.maxima.maximaAttendance.daos.UserDAO;
import com.maxima.maximaAttendance.pojos.Holiday;
import com.maxima.maximaAttendance.pojos.TimeLog;
import com.maxima.maximaAttendance.pojos.User;

public class Report {
	private static List<Holiday> holidayList = new HolidayDAO()
			.getAllHolidays();
	private static Date currentDate = new Date();
	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd-MM-yyyy");

	public List<File> getReportFiles(String month, String year) {
		if (month.equals("select") || year.equals("select")) {
			ServletActionContext.getRequest().getSession()
					.setAttribute("errMsg", "Please select month/year!");
		} else {
			List<TimeLog> tList = new TimeLogDAO().getTimeLogsForMonth(
					month.toString(), year.toString());

			SimpleDateFormat monthFormat = new SimpleDateFormat("MM-yyyy");
			Date dt = null;
			try {
				dt = monthFormat.parse(month + "-" + year);
			} catch (ParseException e1) {
				e1.printStackTrace();
				return null;
			}
			Calendar cal = Calendar.getInstance();
			cal.setTime(dt);

			Map<String, List<Integer>> projectMap = new HashMap<String, List<Integer>>();
			UserDAO userDAO = new UserDAO();
			List<User> allUsers = userDAO.getAllUsers();

			for (User user : allUsers) {
				if (projectMap.containsKey(user.getProject())) {
					projectMap.get(user.getProject()).add(user.getId());
				} else {
					List<Integer> lst = new ArrayList<Integer>();
					lst.add(user.getId());
//					projectMap.put(user.getProject(), lst);
				}
			}

			Map<Integer, List<TimeLog>> timeLogsMapByUserID = new HashMap<Integer, List<TimeLog>>();

			for (User user : allUsers) {
				timeLogsMapByUserID.put(user.getId(), new ArrayList<TimeLog>());
			}

			for (TimeLog timeLog : tList) {
				int x = timeLog.getUser().getId();
				if (timeLogsMapByUserID.containsKey(x)) {
					timeLogsMapByUserID.get(x).add(timeLog);
				} else {
					List<TimeLog> lst = new ArrayList<TimeLog>();
					lst.add(timeLog);
					timeLogsMapByUserID.put(x, lst);
				}
			}
			for (Map.Entry<Integer, List<TimeLog>> entry : timeLogsMapByUserID
					.entrySet()) {

				List<TimeLog> lst = new ArrayList<TimeLog>();
				User u = null;
				if (entry.getValue().size() > 0)
					u = entry.getValue().get(0).getUser();
				else
					u = userDAO.getUser(entry.getKey());

				for (int i = 1; i <= cal
						.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {

					Date rec_date = null;
					try {
						rec_date = dateFormat.parse(i + "-" + month + "-"
								+ year);
					} catch (ParseException e) {

						e.printStackTrace();
						return null;
					}
					if (rec_date.before(currentDate)) {
//						String str = dateFormat.format(rec_date);

						TimeLog x = null;
						for (TimeLog timeLog : entry.getValue()) {
							if (timeLog.getRecordDate().equals(currentDate)) {
								x = timeLog;
								break;
							}
						}
						if (x == null) {
							if (u == null)
								u = new UserDAO().getUser(entry.getKey());
							if (checkIfHoliday(rec_date)) {
								x = new TimeLog(currentDate, u, "Holiday");
							} else {
								x = new TimeLog(currentDate, u, "Leave");
							}
							lst.add(x);
						} else {
							lst.add(x);
						}
					} else {
						break;
					}
				}
				entry.setValue(lst);
			}

			CreateReport createReport = new CreateReport();
			List<File> files = new ArrayList<File>();
			for (Map.Entry<String, List<Integer>> entry : projectMap.entrySet()) {

				Map<Integer, Object[]> data = formatData(timeLogsMapByUserID,
						entry);
				files.add(createReport.generateReport(entry.getKey(), data));
			}
			return files;
		}
		return null;
	}

	public Map<Integer, Object[]> formatData(
			Map<Integer, List<TimeLog>> timeLogsMapByUserID,
			Map.Entry<String, List<Integer>> entry) {
		int count;
		count = 0;
		Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();
		data.put(count++, new Object[] { "User", "Date", "Login Time",
				"Logout Time", "Total No of Hrs" });
		data.put(count++, new Object[] {});

//		for (Integer userID : entry.getValue()) {
//
//			for (TimeLog timeLog : timeLogsMapByUserID.get(userID)) {
//				User u = timeLog.getUser();
//				if (timeLog.getLoginTime() != null
//						&& timeLog.getLogoutTime() != null) {
//					data.put(
//							count++,
//							new Object[] {
//									u.getFirstname() + " " + u.getLastname(),
//									timeLog.getRecordDate(), timeLog.getTimeIn(),
//									timeLog.getTimeOut(), getTimeDiff(timeLog) });
//
//				} else if (timeLog.getLogin_date() != null) {
//					data.put(
//							count++,
//							new Object[] {
//									u.getFirstname() + " " + u.getLastname(),
//									timeLog.getRec_date(), timeLog.getTimeIn(),
//									"-", "-" });
//				} else {
//					data.put(
//							count++,
//							new Object[] {
//									u.getFirstname() + " " + u.getLastname(),
//									timeLog.getRec_date(), timeLog.getComment() });
//				}
//			}
//			data.put(count++, new Object[] {});
//		}
		return data;
	}

	public boolean checkIfHoliday(Date rec_date) {
		SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EEEE");
		if (dayOfWeekFormat.format(rec_date).equals("Saturday")
				|| dayOfWeekFormat.format(rec_date).equals("Sunday"))
			return true;
		else {
			for (Holiday holiday : holidayList) {
				if (dateFormat.format(rec_date).equals(holiday.getDate()))
					return true;
			}
		}
		return false;
	}

	public String getTimeDiff(TimeLog timeLog) {
		Date login = null;
		Date logout = null;
		SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//		try {
//			login = format.parse(timeLog.getLogin_date() + " "
//					+ timeLog.getTimeIn());
//			logout = format.parse(timeLog.getLogout_date() + " "
//					+ timeLog.getTimeOut());
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}

		// in milliseconds
//		long diff = logout.getTime() - login.getTime();
//		long diffMinutes = diff / (60 * 1000) % 60;
//		long diffHours = diff / (60 * 60 * 1000) % 24;
		return null;
//		return diffHours + ":" + diffMinutes;
	}
}
